var app = getApp();

Page({
  data: {
    language: '',
    // goodsData:[],
    goodsData: [],
    dataState: 0,
    showEdit: false,
    // 是否显示面板指示点
    indicatorDots: true,
    // 方向
    vertical: false,
    // 是否自动切换 
    autoplay: true,
    // 自动切换时间间隔
    interval: 4000,
    // 滑动动画时长
    duration: 300,

    integral: "积分",

    isLoadMore: true,
    page: 1,
    totalPage: 0,
    checkAll: false,
    collChecked:false,
    timeOutEvent:'',
    footIdArr:[]
  },
  operateOn() { //切换足迹
    let goodsData = this.data.goodsData;
    if(goodsData.length === 0) {
      wx.showToast({
        title: '您还没有浏览过任何商品',
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    if(!this.data.checkAll) {
      goodsData.map((item,index) => {
        item.goodsList.map((goodsItem,goodsIndex) => {
          goodsItem.maskChecked = false;
        })
      })
        
      
    }
    this.setData({
      checkAll:!this.data.checkAll,
      goodsData
    });
  },
  timeCheck(event) { //时间选择
    let {index,datas} = event.currentTarget.dataset;
    let footIdArr = [];
    let goodsData = this.data.goodsData;
    datas.forEach((goodsItem,goodsIndex) => {
      goodsItem.goodsChecked = event.detail;
      goodsItem.checked = event.detail;
      if(goodsItem.goodsChecked) {
        footIdArr.push(goodsItem.delId);
      }
    })
    goodsData[index].goodsList = datas;
    goodsData[index].checked = event.detail;
    let timeChecked = goodsData.every((item) => item.checked);
    this.setData({
      footIdArr,
      goodsData,
      collChecked:timeChecked
    })
  },
  goodsCheck(event) { //有中文key，需要处理格式
    let {index,goodsindex,datas} = event.currentTarget.dataset;
    let footIdArr = [];
    let goodsDatas = this.data.goodsData;
    goodsDatas[index].goodsList[goodsindex].goodsChecked = !goodsDatas[index].goodsList[goodsindex].goodsChecked;
    let timeChecked = goodsDatas[index].goodsList.every((item) => item.goodsChecked);
    goodsDatas[index].checked = timeChecked;
    goodsDatas[index].goodsList.forEach((goodsItem,goodsIndex) => {
      if(goodsItem.goodsChecked) {
        footIdArr.push(goodsItem.delId);
      }
    })
    let checkedAll = goodsDatas.every((item) => item.checked);
    this.setData({
      goodsData:goodsDatas,
      footIdArr,
      collChecked:checkedAll
    })
  },
  allClick(event) { //全选
    let datas = this.data.goodsData;
    datas.map((item,index) => {
      item.checked = event.detail;
      item.goodsList.map((goodsItem,goodsIndex) => {
        goodsItem.goodsChecked = event.detail;
        goodsItem.checked = event.detail;
      })
    })
    this.setData({
      collChecked:event.detail,
      goodsData:datas
    })
  },
  gtouchstart(event) {
    let {index,goodsindex,goodsitem} = event.currentTarget.dataset;
    this.data.timeOutEvent = setTimeout(() => {
      if(!this.checkAll) {
      this.longPress(index,goodsindex,goodsitem);
      }
    }, 500); //这里设置定时器，定义长按500毫秒触发长按事件
    return false;
  },
  //真正长按后应该执行的内容
  longPress(index,goodsindex,goodsitem) {
    
    this.data.timeOutEvent = 0;
    let goodsData = this.data.goodsData
    goodsData.map((item,index) => {
      item.goodsList.map((goodsItem,goodsIndex) => {
        goodsItem.maskChecked = false;
      })
    })
    if(!this.data.checkAll) {
      goodsData[index].goodsList[goodsindex].maskChecked = true;
      this.setData({
        goodsData:goodsData
      })
    }
    // val.maskChecked = true;
    //执行长按要执行的内容，如弹出菜单
  },
  maskClick(event) { //单选删除
    let {goodsitem,index,goodsindex} = event.currentTarget.dataset;
    this.delData(goodsitem.delId,index,goodsindex);
  },
  //手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
  showDeleteButton(event) {
    let goodsItem = event.currentTarget.dataset.goodsitem;
    clearTimeout(this.data.timeOutEvent); //清除定时器
    if (this.data.timeOutEvent != 0) {
      //这里写要执行的内容（如onclick事件）
      console.log("点击但未长按");
      if(!this.data.checkAll && !goodsItem.maskChecked) { //未开启选择跳转
        if (goodsItem.owner_id != 0) {
          //goodsO2O
          // wx.navigateTo({
          //   url: "/packageA/detail_v2/detail_v2?id=" + goodsItem.id + "&tag=o2o" + "&store_id=" + goodsItem.owner_id,
          // });
        } else {
          wx.navigateTo({
            url: '/packageA/detail_v2/detail_v2?id=' + goodsItem.id
          });
        }
      }
      
    }
    return false;
  },
  //如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
  gtouchmove() {
    clearTimeout(this.data.timeOutEvent); //清除定时器
    this.data.timeOutEvent = 0;
  },
  footListDel() {
    this.delData();
  },
  // 单条删除
  delData: function(id,index,goodsindex) {
    var that = this;
    var url = app.getNetAddresss("member.member-history.destroy");
    let json = {};
    if(this.data.collChecked) {
      json.has_all = true;
    } else {
      this.data.footIdArr.length == 0?json.id = id:json.id = this.data.footIdArr;
    }
    wx.showModal({
      title: '提示',
      content: '确定要删除足迹么？此操作不可逆！',
      success: function(res) {
        if (res.confirm) {
          console.log('用户点击确定');
          app._postNetWork({
            url: url,
            data:json,
            success: function(res) {
              var _data = res.data;
              if (_data.result == 1) {
                if(!that.data.checkAll && !that.data.collChecked) { //删除商品停留当前板块
                  that.data.goodsData[index].goodsList.length === 1?that.data.goodsData.splice(index,1):that.data.goodsData[index].goodsList.splice(goodsindex,1);
                } else {
                  that.data.page = 1;
                  that._getData();
                }
                that.setData({
                  goodsData:that.data.goodsData,
                  checkAll:false
                });
                // that._getData();
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  success: function() {},
                  fail: function() {}
                });
              } else {
                wx.showToast({
                  title: '数据错误',
                  icon: 'success',
                  duration: 2000,
                  success: function() {},
                  fail: function() {}
                });
              }

            },
            fail: function(res) {}
          });
        }
      }
    });
  },
  // 获取数据
  _getData: function() {
    var that = this;
    let urlStr = app.getNetAddresss("member.member-history.index");
    if(app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.member.history-list");
    }
    app._getNetWork({
      url: urlStr,
      data: {
        page: this.data.page
      },
      showToastIn: false,
      success: (res) => {
        var _data = res.data;
        if (_data.result == 1) {
          this.data.totalPage = _data.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          wx.hideLoading();
          wx.hideNavigationBarLoading();//隐藏导航条加载动画
          //停止下拉刷新
          wx.stopPullDownRefresh();
          let goodsData = [];
          goodsData = _data.data.member_histories;
          let footPrintArr = [];
          footPrintArr[0] = goodsData[0];
          goodsData = this.handlerFootPrint(goodsData,footPrintArr);
          this.setData({
            goodsData
          });
        } else {
          this.data.page = this.data.page - 1;
          this.data.isLoadMore = false;
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: function(res) {}
    });
  },
  handlerFootPrint(datas,footPrintArr) {
    if(datas.length === 0) return []; //没有数据返回空
    let i = 0;
    datas.map((item,index) => {
      item.goodsList = [];
      item.checked = false;
      item.goods.delId = item.id;
      item.goods.vip_level_status = item.vip_level_status;
      item.goods.owner_id = item.owner_id;
      item.goods.option_price = item.option_price;
      item.dataName = this.getDate(item.date_group)
      if(footPrintArr[i].date_group === (item.date_group)) {
        footPrintArr[i].goodsList.push(item.goods);
      } else {
        i++;
        footPrintArr.push(item);
        footPrintArr[i].goodsList.push(item.goods);
      }
      footPrintArr[i].goodsList.map((goodsItem,goodsIndex) => {
        goodsItem.goodsChecked = false;
        goodsItem.maskChecked = false;
      })
      if(this.data.collChecked) {
        item.checked = this.data.collChecked;
        footPrintArr[i].goodsList.map((goodsItem,goodsIndex) => {
          goodsItem.goodsChecked = this.data.collChecked;
        });
      }
      if(item.checked) { //只选择日期分页新增数据判断选中
        footPrintArr[i].goodsList.map((goodsItem,goodsIndex) => {
          goodsItem.goodsChecked = item.checked;
        });
      }
    });
    return footPrintArr;
  },
  getDate(str) { //处理日期时间
    if(!str) return;
    let strArr = str.split('-');
    let year=strArr[0];
    let month=strArr[1].replace("月",'');
    let day=strArr[2];
    let date = (year + '年' + month + '月' + day + '日').toString();
    return date;
  },
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.totalPage) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss("member.member-history.index");
      if(app.globalData.store_alone_temp == 1) {
        // 开启门店独立模块
        urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.member.history-list");
      }
      app._getNetWork({
        url: urlStr,
        data: { page: this.data.page },
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.member_histories;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            let footPrintArr = [];
            footPrintArr[0] = list[0];
            let datas  = this.handlerFootPrint(list,footPrintArr); //处理数据结构
            datas.map((item,index) => {
              if(this.data.goodsData[this.data.goodsData.length -1].date_group === datas[0].date_group) {
                let dataGroup = this.data.goodsData[this.data.goodsData.length -1].goodsList;
                this.data.goodsData[this.data.goodsData.length -1].goodsList = [...dataGroup,...item.goodsList];
                datas.shift() 
              }
            })
            this.setData({
              goodsData : this.data.goodsData.concat(datas),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});

    let value = wx.getStorageSync("integral");
    if (value) {
      this.setData({
        integral: value,
      });
    }
    // 页面渲染完成
  },
  onShow: function() {
    this.setData({
      page: 1
    });
    this._getData();
    this.getiPnoneBottom();
    // 页面显示
  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },

  onReachBottom () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  }
});
